package tech.runchen.gz5055.oms.modules.openapi.controller;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.runchen.gz5055.oms.common.utils.Result;
import tech.runchen.gz5055.oms.modules.openapi.form.BarcodeForm;
import tech.runchen.gz5055.oms.modules.system.entity.BarcodeEntity;
import tech.runchen.gz5055.oms.modules.system.entity.ProductEntity;
import tech.runchen.gz5055.oms.modules.system.service.IBarcodeService;
import tech.runchen.gz5055.oms.modules.system.service.IProductService;

import java.util.List;

/**
 * @author zzj
 */
@RestController
@RequestMapping("/openapi/barcode")
public class OpenApiBarcodeController {

    @Autowired
    private IBarcodeService barcodeService;
    @Autowired
    private IProductService productService;

    @PostMapping("/push")
    public Result push(@Validated @RequestBody List<BarcodeForm> barcodeList) {
        for (BarcodeForm form : barcodeList) {
            BarcodeEntity barcode = barcodeService.queryInfoByBarcodeId(form.getBarcodeId());
            if (barcode == null) {
                barcode = new BarcodeEntity();
                BeanUtil.copyProperties(form, barcode);
                ProductEntity product = productService.queryInfoByProductId(form.getProduct().getProductId());
                barcode.setBarcode(form.getCode());
                barcode.setProductId(product.getId());
                barcode.setProductInfo(product.getProductName() + "（" + product.getModel() + "）" + "【" + product.getFactory() + "】");
                barcodeService.saveBarcode(barcode);
            } else {
                BeanUtil.copyProperties(form, barcode);
                ProductEntity product = productService.queryInfoByProductId(form.getProduct().getProductId());
                barcode.setBarcode(form.getCode());
                barcode.setProductId(product.getId());
                barcode.setProductInfo(product.getProductName() + "（" + product.getModel() + "）" + "【" + product.getFactory() + "】");
                barcodeService.updateBarcode(barcode);
            }
        }
        return Result.success("操作成功");
    }
}
